<!-- 单张图片简单上传 -->
<template>
  <el-upload
    class="avatar-uploader"
    :action="action"
    :show-file-list="false"
    :on-success="uploadSuccess"
    :before-upload="() => {}"
    :headers="{ Authorization: getToken() }"
    accept="image/*"
  >
    <img v-if="modelValue" :src="modelValue" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import type { BaseResponse, MinioResult } from "@/types";
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { computed } from "vue";

const props = withDefaults(defineProps<{
  modelValue: string; // 预览图片 一般由上传成功后后台返回
  size?: string; // 图片上传组件大小
}>(), {
  size: '178px'
});

const size = computed(() => props.size);

const action = `${import.meta.env.VITE_BASE_API}/minio/uploadPic`;

const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();

const uploadSuccess = (
  res: BaseResponse<MinioResult>,
  uploadFile,
  uploadFiles
) => {
  console.log(res);
  if (res.errorCode !== 200) {
    ElMessage.error(res.errorMsg || "图片上传失败");
  } else {
    emit("update:modelValue", res.data.imageUrl);
  }
};
</script>

<style>
/* 头像上传框默认样式 */
.avatar-uploader .avatar {
  width: v-bind(size);
  height: v-bind(size);
  display: block;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: v-bind(size);
  height: v-bind(size);
  text-align: center;
}

/* fix：el-avatar组件显示头像不占满的问题 */
.el-avatar>img {
  flex: 1;
}
</style>
